package cn.ictgu.parse.crawler;

import cn.ictgu.config.OtherParseConfig;
import cn.ictgu.dto.VideoInfo;
import cn.ictgu.dao.model.Juji;
import cn.ictgu.parse.VideoParse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.nodes.Document;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 爱奇艺
 * Created by Silence on 2017/1/7.
 */
public class Iqiyi extends VideoParse {

  private static final String IQIYI = "爱奇艺";

  private static final String IQIYI_VIDEOS = "http://cache.video.qiyi.com/jp/avlist/%s/1/50/";

  @Override
  public VideoInfo parseVideoFromUrl(String videoUrl) {
    VideoInfo videoInfo = createVideoInfoWithCopyRight(IQIYI, videoUrl, OtherParseConfig.OFFICIAL_NAME, OtherParseConfig.OFFICIAL_WEBSITE);
    Document document = getDocument(videoUrl);
    String title = document.select("title").text();
    videoInfo.setTitle(title);
    String playUrl = commenParse(videoUrl);
    videoInfo.setPlayUrl(playUrl);
    videoInfo.setType("NORMAL");
    return videoInfo;
  }

  @Override
  public List<Juji> parseJujiFromUrl(String videoUrl) {
    List<Juji> jujis = new ArrayList<>();
    Document document = getDocument(videoUrl);
    Matcher matcher = Pattern.compile("albumId:(.*?),").matcher(document.html());
    if (matcher.find()) {
      String vid = matcher.group(1);
      String videosAPI = String.format(IQIYI_VIDEOS, vid);
      String data = getDocument(videosAPI).body().text().replace("var tvInfoJs=","");
      JSONObject jsonObject = JSONObject.parseObject(data);
      JSONArray array = jsonObject.getJSONObject("data").getJSONArray("vlist");
      if (array.size()>0){
        for (int i = array.size() - 1; i >= 0; i--) {
          JSONObject object = array.getJSONObject(i);
          Juji juji = new Juji();
          Integer index = object.getInteger("pd");
          if (index < 10) {
            juji.setIndex("0" + index);
          } else {
            juji.setIndex("" + index);
          }
          juji.setValue(object.getString("vurl"));
          jujis.add(juji);
        }
      }
    }
    return jujis;
  }

}
